/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://github.com/mineadmin
 */
import type { MaProTableColumns, MaProTableExpose } from "@mineadmin/pro-table";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import defaultAvatar from "@/assets/images/defaultAvatar.jpg";
import { ElTag, ElImage } from "element-plus";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import hasAuth from "@/utils/permission/hasAuth.ts";
import { deleteByIds } from "$/attractions/inspection/api/inspectionRecordsResult.ts";
import { page as getDevicesPage } from "$/attractions/inspection/api/inspectionDevices.ts";
import { page as getRecordsPage } from "$/attractions/inspection/api/inspectionRecords.ts";

import { page as getInspectionRecordsPage } from "$/attractions/inspection/api/inspectionRecords.ts";
export default function getTableColumns(
  dialog: UseDialogExpose,
  formRef: any,
  t: any
): MaProTableColumns[] {
  const msg = useMessage();

  // 创建设备列表缓存
  const deviceList = ref<any[]>([]);
  const recordList = ref<any[]>([]);
  const inspectionRecordsList = ref<any[]>([]);
  // 获取设备列表
  onMounted(async () => {
    try {
      const response = await getDevicesPage({ page: 1, pageSize: 1000 });
      if (response.code === 200 && response.data && response.data.list) {
        deviceList.value = response.data.list;
      }
      const response2 = await getRecordsPage({ page: 1, pageSize: 1000 });
      if (response2.code === 200 && response2.data && response2.data.list) {
        recordList.value = response2.data.list;
        console.log("巡检记录列表", recordList.value);
      }
      const response3 = await getInspectionRecordsPage({
        page: 1,
        pageSize: 1000,
      });
      if (response3.code === 200 && response3.data && response3.data.list) {
        inspectionRecordsList.value = response3.data.list;
        console.log("巡检记录列表", inspectionRecordsList.value);
      }
    } catch (error) {
      console.error("获取设备列表失败:", error);
    }
  });

  return [
    {
      type: "selection",
      showOverflowTooltip: false,
      label: () => t("crud.selection"),
    },
    {
      label: "记录ID",
      prop: "inspection_record_id",
      cellRender: ({ row }) => {
        const record = inspectionRecordsList.value.find(
          (item) => item.id === row.inspection_record_id
        );
        return record ? record.name : `记录${row.inspection_record_id}`;
      },
    },
    {
      label: "设备名称",
      prop: "device_id",
      cellRender: ({ row }) => {
        if (!row.device_id) {
          return "未选择设备";
        }
        const device = deviceList.value.find(
          (item) => item.id === row.device_id
        );
        return device ? device.name : `设备${row.device_id}`;
      },
    },
    {
      label: "图片",
      prop: "photo",
      cellRender: ({ row }) => {
        if (!row.photo) {
          return h("span", { style: { color: "#999" } }, "暂无图片");
        }

        // 获取API基础URL
        const env = import.meta.env;
        const baseUrl =
          env.VITE_OPEN_PROXY === "true"
            ? env.VITE_PROXY_PREFIX
            : env.VITE_APP_API_BASEURL;
        const imageUrl = `${baseUrl}${row.photo}`;

        return h(
          ElImage,
          {
            src: imageUrl,
            alt: "商品图片",
            style: {
              width: "60px",
              height: "40px",
              borderRadius: "4px",
              border: "1px solid #ddd",
            },
            fit: "cover",
            previewSrcList: [imageUrl],
            previewTeleported: true,
            onError: () => {
              console.warn("商品图片加载失败:", imageUrl);
            },
          },
          {
            error: () =>
              h(
                "div",
                {
                  style: {
                    width: "60px",
                    height: "40px",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    backgroundColor: "#f5f5f5",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    fontSize: "12px",
                    color: "#999",
                  },
                },
                "加载失败"
              ),
          }
        );
      },
    },
    {
      label: "状态",
      prop: "status",
      cellRender: ({ row }) => {
        return (
          <el-tag type={row.status === 1 ? "success" : "danger"}>
            {row.status === 1 ? "正常" : "异常"}
          </el-tag>
        );
      },
    },
    {
      type: "operation",
      label: () => t("crud.operation"),
      operationConfigure: {
        actions: [
          {
            name: "edit",
            icon: "material-symbols:person-edit",
            show: ({ row }) =>
              hasAuth("inspection_result:inspectionResult:update"),
            text: () => t("crud.edit"),
            onClick: ({ row }) => {
              dialog.setTitle(t("crud.edit"));
              dialog.open({ formType: "edit", data: row });
            },
          },
          {
            name: "del",
            icon: "mdi:delete",
            text: () => t("crud.delete"),
            show: ({ row }) =>
              hasAuth("inspection_result:inspectionResult:delete"),
            onClick: ({ row }, proxy: MaProTableExpose) => {
              msg.delConfirm(t("crud.delDataMessage")).then(async () => {
                const response = await deleteByIds([row.id]);
                if (response.code === ResultCode.SUCCESS) {
                  msg.success(t("crud.delSuccess"));
                  proxy.refresh();
                }
              });
            },
          },
        ],
      },
    },
  ];
}
